import axios from 'axios'
// import { MaterialApi } from './MaterialApi'
// import { ContactApi } from './ContactApi'
// import { OrderApi } from './OrderApi'

// import { OrderTemplateApi } from './OrderTemplateApi'
// import { UserApi } from './UserApi'
// import { JobRecordApi } from './JobRecordApi'
import { UserModel } from '~/model'

export const user = new UserModel()

const PROTOCOL = window.location.protocol
const SERVER_VIA_VPN = '10.8.0.1'
const salt = '4A953799-B4C6-CABA-8F80-7CF009DEC50D'

/** 服务器位置配置 */
enum DevApiConfig {
  Local, // 本地
  Vpn, // Vpn
}

///////////
// 选择连接方式
// const devApiConfig = DevApiConfig.Local as DevApiConfig // 使用本地服务器
const devApiConfig = DevApiConfig.Vpn as DevApiConfig // 使用VPN的服务器

let HOSTNAME: string

if (process.env.NODE_ENV === 'development') { // 开发环境
  if (devApiConfig === DevApiConfig.Local) {
    HOSTNAME = '127.0.0.1'
  }
  else { // devApiConfig === DevApiConfig.Vpn
    HOSTNAME = SERVER_VIA_VPN
  }
}
else { // 生产环境
  HOSTNAME = window.location.hostname
}

const PREFIX = 'erp'
function getBaseUrl(): string {
  if (PROTOCOL === 'http:') {
    return `${PROTOCOL}//${HOSTNAME}:${8000}/${PREFIX}/`
  }
  else {
    return `${PROTOCOL}//${HOSTNAME}/${salt}/api/${PREFIX}/`
  }
}
export const baseUrl = getBaseUrl()

axios.interceptors.request.use((config) => {
  if (user.userId) {
    config.headers.Authorization = `Token ${user.token}`
    // console.info(`Authorized as ${user.name}`)
  }
  else {
    console.warn('Unauthorized!', user)
  }
  config.baseURL = baseUrl

  // console.log(JSON.stringify(config))

  Loading.state = true
  return config
}, (error) => {
  return Promise.reject(error)
})

axios.interceptors.response.use((response) => {
  // console.log(response)

  Loading.state = false
  return response
}, (error) => {
  if (error.response.status === 401) {
    Loading.state = false
    console.log(error)
    console.warn('User', user)
    location.href = '/login'
  }

  return Promise.reject(error)
})

export async function safe(action: () => Promise<void>): Promise<boolean> {
  try {
    await action()
    return true
  }
  catch (err) {
    console.error('falseOnCatch')
    console.error(err)
    return false
  }
}

// 服务器的简单数据返回形式
export interface SimpleResult {
  success: boolean,
  message?: string,
}

// 避免引起搜索混乱被禁用
// const Api = {
//   Material: MaterialApi,
//   Contact: ContactApi,
//   Order: OrderApi,
//   // OrderTemplate: OrderTemplateApi,
//   User: UserApi,
//   JobRecord: JobRecordApi,
// }

// setInterval(() => {
//   console.log(`Loading ${Loading.state}`);
// }, 1000)
// export default Api
